package com.shjy.driver.jg;

import android.content.Context;
import android.content.SharedPreferences;
import android.text.TextUtils;
import android.util.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.shjy.driver.util.Const;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

/**
 * Created by ld on 2017/6/26.
 */

public class JGUtil {

    private static final String TAG = "JGUtil";

    public static void setAlias(Context context) {

        SharedPreferences sharedPreferences = context.getSharedPreferences("cookie", Context.MODE_PRIVATE);
        final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");
        final String phone = sharedPreferences.getString(Const.KEY_PHONE, "");
        final String registrationID = JPushInterface.getRegistrationID(context);

        Log.d(TAG, "setAlias [ uid = " + driverUuid + ", tel = " + phone + ", registrationID = " + registrationID + " ]");

        if (!TextUtils.isEmpty(driverUuid) && !TextUtils.isEmpty(phone) && !TextUtils.isEmpty(registrationID)) {

            String url = Const.DOMAIN + "driverDevice/addDriverDevice.htm";
            RequestQueue requestQueue = Volley.newRequestQueue(context);

            StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
                @Override
                public void onResponse(String s) {
                    Log.d(TAG, "onResponse " + s);
                }
            }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError volleyError) {
                    Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
                }
            }) {
                @Override
                protected Map<String, String> getParams() throws AuthFailureError {
                    Map<String, String> map = new HashMap<String, String>();
                    map.put("token", driverUuid);
                    map.put("registionID", registrationID);
                    map.put("phone", phone);
                    map.put("deviceType", "1"); // 1--android；2--ios
                    Log.d(TAG, "getParams " + map);
                    return map;
                }
            };

            requestQueue.add(stringRequest);

            JPushInterface.setAlias(context, phone, new TagAliasCallback() {
                @Override
                public void gotResult(int i, String s, Set<String> set) {
                    Log.d(TAG, s);
                }
            });
        }
    }
}
